package com.ht.interfaces.request.link;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.ht.api.db.Entity;
import com.ht.api.db.annotate.FuncCall;
import com.ht.api.db.annotate.FuncGroup;
import com.ht.api.db.annotate.FuncId;
import com.ht.api.db.annotate.FuncName;
import com.ht.api.db.annotate.FuncParam;
import com.ht.api.db.annotate.FuncParams;
import com.ht.api.db.bean.DataResult;
import com.ht.api.db.bean.SessionBean;
import com.ht.api.db.request.IHandleRequest;
import com.ht.api.db.util.MqUtil;
import com.ht.interfaces.service.LinkService;
import com.ht.interfaces.utils.CallTestUtil;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@FuncId("1912788783665909760")
@FuncGroup("H5接口")
@FuncParams({
		@FuncParam(name = "调查问卷ID", code = "questionnaire_id", value = "1912439849445625856"),
		@FuncParam(name = "答题内容", code = "content", value = "答题内容json")
})

@FuncCall
@FuncName("提交调查问卷")
public class QuestionnaireSubmit implements IHandleRequest {

	@Override
	public void execute(SessionBean me, JSONObject param, DataResult result) {
		List<Entity> dataList = new ArrayList<>();

		Entity questionnaireFillDetails = Entity.create("questionnaire_fill_details");
		questionnaireFillDetails.set("questionnaire_id", param.get("questionnaire_id"));
		questionnaireFillDetails.set("openid", me.getOpenid());
		questionnaireFillDetails.set("fill_time", DateUtil.now());
		questionnaireFillDetails.set("questionnaire_info", param.get("content"));

		dataList.add(questionnaireFillDetails);

		String questionnaireId = param.getStr("questionnaire_id");

		for (Object contentObj : param.getJSONArray("content")) {
			JSONObject question = JSONUtil.parseObj(contentObj);
			String questionId = question.getStr("id");

			JSONArray answers = question.getJSONArray("answers");
			for (int i = 0; i < answers.size(); i++) {
				JSONObject answer = answers.getJSONObject(i);
				if (answer.getBool("is_checked")) {
					Entity details = Entity.create("questionnaire_answer_fill_details");
					details.set("questionnaire_id", questionnaireId);
					details.set("question_id", questionId);
					details.set("answer_id", answer.get("id"));
					details.set("openid", me.getOpenid());

					dataList.add(details);
				}
			}
		}

		// 通过mq发送请求
		MqUtil.send(me.getTenantId(), dataList);

		log.info("提交调查问卷。。。。。。。");

		result.setMsg("感谢参与哦~");
	}

	public static void main(String[] args) {

		CallTestUtil.autoTest(new Object(){}.getClass().getEnclosingClass().getSimpleName());
	}
}
